package com.apex.service.impl;

import com.apex.dto.Result;
import com.apex.entity.SeckillVoucher;
import com.apex.entity.VoucherOrder;
import com.apex.mapper.VoucherOrderMapper;
import com.apex.service.ISeckillVoucherService;
import com.apex.service.IVoucherOrderService;
import com.apex.utils.RedisIdWorker;
import com.apex.utils.UserHolder;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;


@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Override
    public Result seckillVoucher(Long voucherId) {
//        1.根据优惠券id获取优惠券信息
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);

//        2. 判断优惠券是否过期或者余额不足
        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())) {
            // 尚未开始
            return Result.fail("秒杀尚未开始！");
        }

        // 3.判断秒杀是否已经结束
        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())) {
            // 尚未开始
            return Result.fail("秒杀已经结束！");
        }

        // 4.判断库存是否充足
        if (seckillVoucher.getStock() < 1) {
            // 库存不足
            return Result.fail("库存不足！");
        }

//       扣减库存并创建订单
        boolean success = seckillVoucherService.update().setSql("stock = stock - 1").eq("voucher_id", voucherId).gt("stock",0).update();
        if (!success){
            return Result.fail("库存不足！");
        }

        return createVoucherOrder(voucherId);
    }

    @Transactional
    public Result createVoucherOrder(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        synchronized (userId.toString().intern()){
            Integer count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
            if (count > 0){
                Result.fail("用户已经购买一次了!");
            }
//        创建订单
            VoucherOrder voucherOrder = new VoucherOrder();
//        订单id
            long orderId = redisIdWorker.nextId("order");
            voucherOrder.setId(orderId);

//        用户id
            voucherOrder.setUserId(userId);

//        代金券id
            voucherOrder.setVoucherId(voucherId);
            save(voucherOrder);
            return Result.ok(orderId);
        }
    }


}
